package com.atguigu.chapter07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/19 10:10
 */
public class Flink08_Widow_Aggregate {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            .aggregate(
                new AggregateFunction<WaterSensor, Tuple2<Integer, Long>, Double>() {
                    // 创建一个累加器: 每个key执行一次
                    @Override
                    public Tuple2<Integer, Long> createAccumulator() {
                        System.out.println("Flink08_Widow_Aggregate.createAccumulator");
                        return Tuple2.of(0, 0L);  // f0: 表示水位  f1: 表示个数
                    }
    
                    // 累加: 每来一个元素执行一次
                    @Override
                    public Tuple2<Integer, Long> add(WaterSensor value, Tuple2<Integer, Long> acc) {
                        System.out.println("Flink08_Widow_Aggregate.add");
                        return Tuple2.of(acc.f0 + value.getVc(), acc.f1 + 1);
                    }
    
                    //返回最终结果: 窗口关闭的时候调用这个方法, 把结果放入后面的流中
                    @Override
                    public Double getResult(Tuple2<Integer, Long> acc) {
                        System.out.println("Flink08_Widow_Aggregate.getResult");
                        return acc.f0 * 1.0 / acc.f1;
                    }
    
                    // 合并两个累加器: 只有sessionwindow才会使用, 其他的无效
                    @Override
                    public Tuple2<Integer, Long> merge(Tuple2<Integer, Long> a, Tuple2<Integer, Long> b) {
                        System.out.println("Flink08_Widow_Aggregate.merge");
                        return null;
                    }
                },
                new ProcessWindowFunction<Double, String, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context context,
                                        Iterable<Double> elements,
                                        Collector<String> out) throws Exception {
                        out.collect(key + "_" + elements.iterator().next());
                    }
                }
            )
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
